package com.ddstation.onsitelaw.service;

import com.ddstation.common.util.IdGenerateUtil;
import com.ddstation.onsitelaw.entity.DtHealthManageInstitutionEntity;
import com.ddstation.onsitelaw.entity.DtInvsManageInstitutionEntity;
import com.ddstation.onsitelaw.entity.auditentity.DdDoctorEntity;
import com.ddstation.onsitelaw.entity.auditentity.MaDataDictionaryEntity;
import com.ddstation.onsitelaw.mapper.DtHealthManageInstitutionMapper;
import com.ddstation.onsitelaw.mapper.DtInvsManageInstitutionMapper;
import com.ddstation.onsitelaw.mapper.MaDataDictionaryMapper;
import com.ddstation.onsitelaw.model.AccountModel;
import com.ddstation.onsitelaw.utils.Constant;
import com.ddstation.onsitelaw.utils.MultipartFileToFile;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Lazy
public class DataImportServiceImpl implements DataImportService {
    private static final Logger log = LoggerFactory.getLogger(DataImportServiceImpl.class);
    @Inject
    private DtInvsManageInstitutionMapper dtInvsManageInstitutionMapper;

    @Inject
    private DtHealthManageInstitutionMapper dtHealthManageInstitutionMapper;

    @Inject
    private MaDataDictionaryMapper maDataDictionaryMapper;

    @Override
    public Integer downloadTemplate(HttpServletResponse response, HttpServletRequest request) {

        try {
            //获取要下载的模板名称
            String fileName = "importTemplate.xlsx";
            //设置要下载的文件的名称
            response.setHeader("Content-disposition", "attachment;fileName=" + fileName);
            //通知客服文件的MIME类型
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            //获取文件的路径
            String filePath = getClass().getResource("/excelTemplate/" + fileName).getPath();
            FileInputStream input = new FileInputStream(filePath);
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = input.read(b)) != -1) {
                out.write(b, 0, len);
            }
            //修正 Excel在“xxx.xlsx”中发现不可读取的内容。是否恢复此工作薄的内容？如果信任此工作簿的来源，请点击"是"
            response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
            input.close();
            return 1;
        } catch (Exception ex) {
            log.error("getApplicationTemplate :", ex);
            return 0;
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(MultipartFile file, AccountModel account) throws Exception {
        //获取卫监机构
        Example example = new Example(DtInvsManageInstitutionEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("province", account.getManageInstitutionEntity().getProvince());
        criteria.andEqualTo("city", account.getManageInstitutionEntity().getCity());
        criteria.andIsNotNull("county");
        criteria.andNotEqualTo("county", "");
        List<DtInvsManageInstitutionEntity> invsList = dtInvsManageInstitutionMapper.selectByExample(example);


        File excel = MultipartFileToFile.multipartFileToFile(file);
        //.是特殊字符，需要转义
        String[] split = excel.getName().split("\\.");
        Workbook wb = null;
        //根据文件后缀（xls/xlsx）进行判断
        if ("xls".equals(split[1])) {
            //文件流对象
            FileInputStream fis = new FileInputStream(excel);
            wb = new HSSFWorkbook(fis);
        } else if ("xlsx".equals(split[1])) {
            wb = new XSSFWorkbook(excel);
        }
        //机构信息sheet页 0
        Sheet institutionSheet = wb.getSheetAt(0);
        Map<String, String> institutionMap = insertInstitution(institutionSheet, account, invsList);

        //医生信息sheet页 1
        Sheet doctorSheet = wb.getSheetAt(1);
        insertDoctor(doctorSheet, institutionMap);

    }

    Map<String, String> insertInstitution(Sheet institutionSheet, AccountModel account, List<DtInvsManageInstitutionEntity> invsList) {
        //第一行是列名，所以不读
        int firstRowIndex = institutionSheet.getFirstRowNum() + 1;
        int lastRowIndex = institutionSheet.getLastRowNum();

        List<DtHealthManageInstitutionEntity> institutionEntityList = new ArrayList<>();
        Map<String, String> institutionMap = new HashMap<>();
        //遍历行
        for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
            DtHealthManageInstitutionEntity institution = new DtHealthManageInstitutionEntity();
            institution.setId(IdGenerateUtil.idGenerateFromTime("04"));
            institution.setSourceType(4);
            institution.setProvince(account.getManageInstitutionEntity().getProvince());
            institution.setCity(account.getManageInstitutionEntity().getCity());
            institution.setUnderInvs(1);
            institution.setStatus(0);
            institution.setIsRepeat(0);
            Row row = institutionSheet.getRow(rIndex);
            if (row != null) {
                //机构名称
                Cell cell1 = row.getCell(0);
                institution.setName(ObjectUtils.isEmpty(cell1) ? "" : cell1.toString());
                //行政区划
                Cell cell2 = row.getCell(1);
                if (!ObjectUtils.isEmpty(cell2)) {
                    for (DtInvsManageInstitutionEntity item : invsList) {
                        if (item.getName().contains(cell2.toString())) {
                            institution.setCounty(item.getCounty());
                            break;
                        }
                    }
                }
                //机构地址
                Cell cell4 = row.getCell(2);
                institution.setAddress(ObjectUtils.isEmpty(cell4) ? "" : cell4.toString());
                //开始日期
                Cell cell5 = row.getCell(3);
                institution.setOccupationalLicenceStartDate(ObjectUtils.isEmpty(cell5) ? null : cell5.getDateCellValue());
                //有效日期
                Cell cell6 = row.getCell(4);
                institution.setOccupationalLicenceEndDate(ObjectUtils.isEmpty(cell6) ? null : cell6.getDateCellValue());
                //诊疗科目代码
                Cell cell8 = row.getCell(6);
                if (!ObjectUtils.isEmpty(cell8)) {
                    institution.setTechnicalOffices(getRegExTechnicalOffices(cell8.toString()));
                }
                //统一社会信用代码
                Cell cell9 = row.getCell(7);
                institution.setOccupationalLicenceCd(ObjectUtils.isEmpty(cell9) ? "" : cell9.toString());
                institutionEntityList.add(institution);
                //机构名称+区域
                String str = institution.getName().trim() + cell2.toString().trim();
                institutionMap.put(str, institution.getId());
            }
        }
        //新增机构
        if (!ObjectUtils.isEmpty(institutionEntityList)) {
            int insertLength = institutionEntityList.size();
            int i = 0;
            while (insertLength > 600) {
                dtHealthManageInstitutionMapper.insertInstitutions(institutionEntityList.subList(i, i + 600));
                i = i + 600;
                insertLength = insertLength - 600;
            }
            if (insertLength > 0) {
                dtHealthManageInstitutionMapper.insertInstitutions(institutionEntityList.subList(i, i + insertLength));
            }
        }
        return institutionMap;
    }


    void insertDoctor(Sheet doctorSheet, Map<String, String> institutionMap) {
        //第一行是列名，所以不读
        int firstRowIndex = doctorSheet.getFirstRowNum() + 1;
        int lastRowIndex = doctorSheet.getLastRowNum();
        //执业范围
        List<MaDataDictionaryEntity> scopePracticeList = maDataDictionaryMapper.selectByCategoryId(Constant.CODE_SCOPE_PRACTICE);
        //职称
        List<MaDataDictionaryEntity> technicalTitleList = maDataDictionaryMapper.selectByCategoryId(Constant.CODE_TECHNICAL_TITLE);

        List<DdDoctorEntity> doctorEntityList = new ArrayList<>();
        //遍历行
        for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
            DdDoctorEntity doctor = new DdDoctorEntity();
            doctor.setId(IdGenerateUtil.idGenerateFromTime("04"));
            Row row = doctorSheet.getRow(rIndex);
            if (row != null) {
                //医生姓名
                Cell cell2 = row.getCell(0);
                doctor.setName(ObjectUtils.isEmpty(cell2) ? "" : cell2.toString());
                //医生身份证
                Cell cell3 = row.getCell(1);
                doctor.setIdCard(ObjectUtils.isEmpty(cell3) ? "" : cell3.toString());
                //执业证书编码
                Cell cell6 = row.getCell(2);
                doctor.setDoctorLicence(ObjectUtils.isEmpty(cell6) ? "" : cell6.toString());
                //资格证书编码
                Cell cell7 = row.getCell(3);
                doctor.setQualification(ObjectUtils.isEmpty(cell7) ? "" : cell7.toString());
                // 执业范围
                Cell cell8 = row.getCell(4);
                if (!ObjectUtils.isEmpty(cell8)) {
                    String[] scopePracticeCellList = cell8.toString().trim().replace("专业", "").split(",");
                    String scopePracticeStr = null;
                    for (MaDataDictionaryEntity scopePractice : scopePracticeList) {
                        for (String scopePracticeCell : scopePracticeCellList) {
                            if (scopePractice.getFullName().equals(scopePracticeCell)) {
                                scopePracticeStr += "," + scopePractice.getValue();
                            }
                        }

                    }
                    doctor.setScopePractice(StringUtils.isEmpty(scopePracticeStr) ? null : scopePracticeStr.substring(1));
                }

                //任职资格（职称）
                Cell cell10 = row.getCell(5);
                if (!ObjectUtils.isEmpty(cell10)) {
                    String technicalTitleCell = cell10.toString().trim();
                    for (MaDataDictionaryEntity technicalTitle : technicalTitleList) {
                        if (technicalTitle.getFullName().equals(technicalTitleCell)) {
                            doctor.setTechnicalTitle(technicalTitle.getValue());
                            break;
                        }
                    }
                }
                //机构名称
                Cell cell11 = row.getCell(6);
                //行政区域
                Cell cell13 = row.getCell(7);
                if (!ObjectUtils.isEmpty(cell11)) {
                    String str = cell11.toString().trim() + cell13.toString().trim();
                    doctor.setInstitutionId(StringUtils.isEmpty(institutionMap.get(str)) ? null : institutionMap.get(str));
                }
                doctor.setLoginPassword("e10adc3949ba59abbe56e057f20f883e");
                if (!StringUtils.isEmpty(doctor.getInstitutionId())) {
                    doctorEntityList.add(doctor);
                }
            }
        }

        //新增医生
        if (!ObjectUtils.isEmpty(doctorEntityList)) {
            int insertLength = doctorEntityList.size();
            int i = 0;
            while (insertLength > 600) {
                List<DdDoctorEntity> insertDoctor = doctorEntityList.subList(i, i + 600);
                //插入医生表
                dtHealthManageInstitutionMapper.insertDoctors(insertDoctor);
                //插入医生机构表
                dtHealthManageInstitutionMapper.insertInstitutionDoctors(insertDoctor);
                i = i + 600;
                insertLength = insertLength - 600;
            }
            if (insertLength > 0) {
                List<DdDoctorEntity> insertDoctor = doctorEntityList.subList(i, i + insertLength);
                //插入医生表
                dtHealthManageInstitutionMapper.insertDoctors(insertDoctor);
                //插入医生机构表
                dtHealthManageInstitutionMapper.insertInstitutionDoctors(insertDoctor);
            }
        }

    }


    String getRegExTechnicalOffices(String ticketStr) {
        //可以在中括号内加上任何想要替换的字符，实际上是一个正则表达式
        String regEx = "[\n`~!@#$%^&*()+=|{}':',\\[\\]<>?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？\u4e00-\u9fa5 ^[A-Za-z]+$ ^[A-Z]+$ ^[a-z]+$]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(ticketStr);
        String newString = m.replaceAll("").trim().replace("/", ",").replace(";", ",");
        if (",".equals(newString.substring(0, 1))) {
            newString = newString.substring(1);
        }
        return newString;
    }
}
